package cn.xkai.exercise.a;

/**
 * @description: 搜索插入位置
 * 自己的思路：定义一个值接收插入索引，如果相等，直接返回索引值，如果小于就把当前索引后面一位赋值
 * 借鉴的思路：判断当前值是否大于等于插入值，即返回索引位置
 * 心得：自己的思路进行了一次满循环，借鉴的思路只需判断到索引位置返回即可，更快，(其他解法：二分法)
 * @author: kaixiang
 * @date: 2022-06-19
 **/
public class Solution3 {
    public int searchInsert(int[] nums, int target) {
        int targetIndex = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                return i;
            }
            if (nums[i] < target) {
                targetIndex = i + 1;
            }
        }
        return targetIndex;
    }

    public int searchInsertRefer(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] >= target) {
                return i;
            }
        }
        return nums.length;
    }

    public int searchInsertTwo(int[] nums, int target) {
        // 二分法
        int left = 0, right = nums.length - 1;
        while (left <= right) {
            // 防止 left+right 整型溢出
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return left;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 4, 5};
        int target = 3;
        Solution3 solution3 = new Solution3();
        System.out.println(solution3.searchInsert(nums, target));
    }
}
